import Qs from 'qs'
import md5 from 'js-md5'

export const HEADER_APPID = 'App-Auth-appid'
export const HEADER_REQURL = 'App-Auth-reqUrl'
export const HEADER_TIMESTAMP = 'App-Auth-timestamp'
export const HEADER_NONCESTR = 'App-Auth-nonceStr'
export const HEADER_SIGN = 'App-Auth-sign'
export const APPID = 'htappid'
const APPSECRET = 'appsecret'
export const APP_AUTH_ENABLE = true

export const generateSignJson = (reqUrl, timestamp, nonceStr, data) => {
    let params = {
        'appid': APPID,
        'nonceStr': nonceStr,
        'timestamp': timestamp,
        'reqUrl': reqUrl,
        'postJsonStr': JSON.stringify(data)
    }
    return md5.hex(generateStringFromJsonObj(params) + APPSECRET).toUpperCase()
}

export const generateSignQs = (reqUrl, timestamp, nonceStr, data) => {
    let params = {
        'appid': APPID,
        'nonceStr': nonceStr,
        'timestamp': timestamp,
        'reqUrl': reqUrl
    }
    for (let key in data) {
        params[key] = data[key]
    }
    return md5.hex(generateStringFromJsonObj(params) + APPSECRET).toUpperCase()
}

export const generateSignGet = (reqUrl, timestamp, nonceStr) => {
    let params = {
        'appid': APPID,
        'nonceStr': nonceStr,
        'timestamp': timestamp,
        'reqUrl': reqUrl
    }
    if (reqUrl.indexOf('?') > 0) {
        let urlAndQueryString = reqUrl.split('?')
        params.reqUrl = urlAndQueryString[0]
        let queryString = urlAndQueryString[1]
        if (queryString) {
            // Qs.parse(queryString)，对c=c&a=a&a=b&b=b这样的字符串，最后parse后得到是a: ['a', 'b']
            let qStrJsonObj = Qs.parse(queryString)
            for (let key in qStrJsonObj) {
                params[key] = qStrJsonObj[key]
            }
        }
    } 
    return md5.hex(generateStringFromJsonObj(params) + APPSECRET).toUpperCase()
}

/**
 * 从JSON对象中获取请求需要加密的字符串
 * 如果是
 *  {
 *      a: ['a','b']
 *  }
 * 的数组形式，则转化后为a=a,b，后台对应的也应该是a=a,b的形式
 * @param {*} jsonObj 
 */
export const generateStringFromJsonObj = (jsonObj) => {
    let keys = []
    for (let key in jsonObj) {
        keys.push(key)
    }
    keys.sort()
    let string = ''
    keys.forEach(key => {
        if (jsonObj[key] && (jsonObj[key] + '').trim()) {
            if (string === '') {
                string = string + key + '=' + jsonObj[key]
            } else {
                string = string + '&' + key + '=' + jsonObj[key]
                
            }
        }
    })
    return string
}